//
//  MSEditUserInfo.m
//  MS
//
//  Created by Yuan on 13-4-14.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSEditUserInfo.h"
#import <QuartzCore/QuartzCore.h>
#import "UIImageView+WebCache.h"
#import "MSEditUserCell.h"

#import "MSEnterVC.h"

#import "MSTagsVC.h"

#define CELL_ITEM_KEY_TITLE @"title" //标题
#define CELL_ITEM_KEY_Type @"type"
#define CELL_ITEM_KEY_VALUE @"value"//显示出来的值
#define CELL_ITEM_KEY_STYLE @"style"//cell的样式
#define CELL_ITEM_KEY_HEIGHT @"height"//cell的高度
#define CELL_ITEM_KEY_ACTION @"action"//点击事件

const NSString *defaultCellHeight = @"44";

@interface MSEditUserInfo ()<UITableViewDataSource,UITableViewDelegate,UniversalDelegate,TagsVCDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate>
{
    UIImage *selectImage;
    UITableView *listTableView;
    NSMutableArray *dataSources;
    NSMutableDictionary *selectItem;
    
    NSMutableDictionary *userInfo;

    UIPickerView *pickerView;
    NSMutableDictionary *provices;
    NSMutableArray *proviceArray;
    NSMutableArray *areasArray;
    NSString *proviceName;
    NSString *cityName;
    NSInteger compoentOneSelectedIndex;
    NSInteger compoentTwoSelectedIndex;
    
    UIView *maskView;
    
    int userSex;
}
@property(nonatomic,retain)NSMutableDictionary *userInfo;
@property(nonatomic,retain) UITableView *listTableView;
@property(nonatomic,retain) NSMutableArray *dataSources;
@property(nonatomic,retain) UIPickerView *pickerView;
@property(nonatomic,retain)NSMutableDictionary *provices;
@property(nonatomic,retain)NSMutableArray *proviceArray;
@property(nonatomic,retain)NSMutableArray *areasArray;
@end

@implementation MSEditUserInfo
@synthesize dataSources;
@synthesize listTableView;
@synthesize pickerView;
@synthesize provices;
@synthesize proviceArray;
@synthesize areasArray;
@synthesize userInfo;

-(void)dealloc
{
    userInfo = nil;
    self.pickerView = nil;
    areasArray = nil;
    proviceArray = nil;
    pickerView = nil;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        dataSources = [[NSMutableArray alloc]init];
        

        proviceName = @"";  cityName = @"";
        compoentOneSelectedIndex = 0; compoentTwoSelectedIndex = 0;
                
        NSString *path_ = [[NSBundle mainBundle] pathForResource:@"provice" ofType:@"plist"];
        provices = [[NSMutableDictionary alloc]initWithContentsOfFile:path_];
        
        NSArray *pArray = [provices objectForKey:@"provices"];
        
        NSArray *rArray = [pArray sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2)
                           {
                               NSNumber * id1 = [NSNumber numberWithInt:[[obj1 objectForKey:@"id"] intValue]];
                               NSNumber * id2 = [NSNumber numberWithInt:[[obj2 objectForKey:@"id"] intValue]];
                               NSComparisonResult result = [id2 compare:id1];
                               return result == NSOrderedAscending;
                           }];
        proviceArray = [[NSMutableArray alloc]initWithArray:rArray];
        
        areasArray = [[NSMutableArray alloc]initWithArray:[provices objectForKey:[[proviceArray objectAtIndex:0] objectForKey:@"id"]]];
        
        NSDictionary *info = [[MSSetting sharedSetting]getAccountInfo];
        
        userInfo = [[NSMutableDictionary alloc]initWithDictionary:info];
        
        userSex = [[userInfo objectForKey:@"sex"] intValue];
        
        //上传头像
        NSMutableDictionary *s1_dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         HYLocalizedString(@"上传头像"),CELL_ITEM_KEY_TITLE,
                                         defaultCellHeight,CELL_ITEM_KEY_HEIGHT,
                                         @"0",CELL_ITEM_KEY_STYLE,
                                         nil];
        NSMutableArray *s1_arr = [[NSMutableArray alloc]initWithObjects:s1_dict1, nil];
        [dataSources addObject:s1_arr];
        
        
        NSString *alias = [info objectForKey:@"user_name"];
        
        //基本信息
        NSMutableDictionary *s2_dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         @"昵称",CELL_ITEM_KEY_TITLE,
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:alias],CELL_ITEM_KEY_HEIGHT,
                                         @"alias",CELL_ITEM_KEY_Type,
                                         @"editAlias",CELL_ITEM_KEY_ACTION,
                                         alias,CELL_ITEM_KEY_VALUE,
                                         nil];
        NSMutableDictionary *s2_dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"性别",@"title",
                                         @"2",CELL_ITEM_KEY_STYLE,
                                         defaultCellHeight,CELL_ITEM_KEY_HEIGHT,
                                         nil];
        NSMutableArray *s2_arr = [[NSMutableArray alloc]initWithObjects:s2_dict1,s2_dict2, nil];
        [dataSources addObject:s2_arr];
        
        //介绍
        NSString *chara = [info objectForKey:@"chara"];
        NSMutableDictionary *s3_dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"介绍",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:chara],CELL_ITEM_KEY_HEIGHT,
                                         chara,CELL_ITEM_KEY_VALUE,
                                         nil];
        NSMutableArray *s3_arr = [[NSMutableArray alloc]initWithObjects:s3_dict1, nil];
        [dataSources addObject:s3_arr];
        
        //城市信息
        NSString *tags = [info objectForKey:@"introduce"];
        NSMutableDictionary *s4_dict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         @"标签",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:tags],CELL_ITEM_KEY_HEIGHT,
                                         tags,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        NSString *mobile = [info objectForKey:@"mobile"];
        NSMutableDictionary *s4_dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"手机",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:mobile],CELL_ITEM_KEY_HEIGHT,
                                         mobile,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        NSString *provicecity = [NSString stringWithFormat:@"%@ %@",[info objectForKey:@"province"],[info objectForKey:@"city"]];
        NSMutableDictionary *s4_dict3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"城市",@"title",
                                         @"3",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:provicecity],CELL_ITEM_KEY_HEIGHT,
                                         provicecity,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        NSString *salon = [info objectForKey:@"salon"];
        NSMutableDictionary *s4_dict4 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"沙龙",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:salon],CELL_ITEM_KEY_HEIGHT,
                                         salon,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        NSString *tel = [info objectForKey:@"tel"];
        NSMutableDictionary *s4_dict5 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"电话",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:tel],CELL_ITEM_KEY_HEIGHT,
                                         tel,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        
        NSString *address = [info objectForKey:@"address"];
        NSMutableDictionary *s4_dict6 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         @"地址",@"title",
                                         @"1",CELL_ITEM_KEY_STYLE,
                                         [self getCellHeight:address],CELL_ITEM_KEY_HEIGHT,
                                         address,CELL_ITEM_KEY_VALUE,
                                         nil];
        
        NSMutableArray *s4_arr = [[NSMutableArray alloc]initWithObjects:s4_dict1,s4_dict2,s4_dict3,s4_dict4,s4_dict5,s4_dict6, nil];
        [dataSources addObject:s4_arr];
        
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    listTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    listTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin;
    listTableView.backgroundColor = [UIColor clearColor];
    listTableView.backgroundView = nil;
    listTableView.delegate = self;
    listTableView.dataSource = self;
    listTableView.sectionFooterHeight = 5.0;
    listTableView.sectionHeaderHeight = 5.0;
    [self.view addSubview:self.listTableView];
    
    maskView = [[UIView alloc]initWithFrame:self.view.bounds];
    [maskView setBackgroundColor:[UIColor blackColor]];
    maskView.alpha = 0.4;
    [maskView setHidden:YES];
    [self.view addSubview:maskView];
    UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    [maskView addGestureRecognizer:g];
}

-(void)tapClick:(UITapGestureRecognizer *)g
{
    g.view.hidden = YES;
    UITableViewCell *cell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:3]];
    UITextField *txt = (UITextField *)[cell.contentView viewWithTag:2];
    [txt resignFirstResponder];
    [listTableView setContentOffset:CGPointZero animated:YES];
    [self updateData:[NSString stringWithFormat:@"%@ %@",proviceName,cityName]];
}

-(NSString *)getCellHeight:(NSString*)detailString
{
    if (!detailString || [detailString length]<1) {
        return @"44";
    }
    CGFloat cellDetailLableWidth = 187;
    CGSize size = [detailString sizeWithFont:FONT_NORMAL constrainedToSize:CGSizeMake(cellDetailLableWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
    float height = size.height + 10;
    return [NSString stringWithFormat:@"%f",height<40?40:height];//26为title的高度20和上下margin3
}

- (void)viewDidLoad
{
    [self setTitle:HYLocalizedString(@"编辑个人资料") showBackButton:YES];
    [self setRightItem:HYLocalizedString(@"保存")];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
}

-(void)saveUserInfo
{
    
    if (![userInfo objectForKey:@"city_id"] || ![userInfo objectForKey:@"province_id"])
    {
        return  [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请选择所在区域!")];
    }
    
    //性别
    [userInfo setObject:[NSNumber numberWithInt:userSex] forKey:@"sex"];
    
    //介绍
    UITableViewCell *charaCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    if ([charaCell.detailTextLabel.text length]>0)
    {
        [userInfo setObject:charaCell.detailTextLabel.text forKey:@"chara"];
    }
    
    //标签
    UITableViewCell *introduceCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    if ([introduceCell.detailTextLabel.text length]>0)
    {
        [userInfo setObject:introduceCell.detailTextLabel.text forKey:@"introduce"];
    }
    
    //手机
    UITableViewCell *mobileCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:3]];
    if ([mobileCell.detailTextLabel.text length]>0)
    {
        [userInfo setObject:mobileCell.detailTextLabel.text forKey:@"mobile"];
    }
    
    //沙龙
    UITableViewCell *salonCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:3]];
    if ([salonCell.detailTextLabel.text length]<3)
    {
        return  [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请填写沙龙的全称!")];
    }
    [userInfo setObject:salonCell.detailTextLabel.text forKey:@"salon"];
    
    
    //电话
    UITableViewCell *phoneCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:3]];
    if ([phoneCell.detailTextLabel.text length]>0)
    {
        [userInfo setObject:phoneCell.detailTextLabel.text forKey:@"tel"];
    }
    
    //地址
    UITableViewCell *addressCell = [listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:3]];
    if ([addressCell.detailTextLabel.text length]>0) {
        [userInfo setObject:addressCell.detailTextLabel.text forKey:@"address"];
    }
    
    [userInfo setObject:[[MSSetting sharedSetting]getAccountID] forKey:@"uid"];
    
    [WebService  getRequestAction:APIUserInfoSet
                            param:userInfo
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             [[MSSetting sharedSetting]setAccountInfo:[info objectForKey:@"result"]];
             [MSTool showAlert:@"保存成功！"];
             [self.navigationController popViewControllerAnimated:YES];
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}


-(void)rightBarButtonItemAction:(UIButton *)btn
{
    if (selectImage)
    {
        [self startUploadImage];
    }
    else
    {
        [self saveUserInfo];
    }
}

-(void)startUploadImage
{
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                       APISetUserAvatar,@"action",[[MSSetting sharedSetting] getAccountID],@"uid", nil];
    [WebService uploadImage:selectImage param:p labelText:HYLocalizedString(@"上传头像") success:^(NSDictionary *info,NSError *error)
     {
         HYLog(@"%@",info);
         [self saveUserInfo];         
     } failure:^(id info ,NSError *error){
         [MSTool showAlert:error.localizedDescription];
     }];
}


-(void)ImageTagsVCFinsihed:(NSString *)info
{
    HYLog(@"%@",info);
    [self updateData:info];
}

-(void)updateData:(id)info
{
    [selectItem setObject:info forKey:CELL_ITEM_KEY_VALUE];
    [selectItem setObject:[self getCellHeight:info] forKey:CELL_ITEM_KEY_HEIGHT];
    [self.listTableView reloadData];
    
}


#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [dataSources count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[dataSources objectAtIndex:section] count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 15;
    }
    return 0;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *item = [[dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return [[item objectForKey:CELL_ITEM_KEY_HEIGHT] floatValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *item = [[dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSString *CellIdentifier = [item objectForKey:CELL_ITEM_KEY_STYLE];
    
    MSEditUserCell *cell = (MSEditUserCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if ([CellIdentifier intValue] == 0)
    {
        if (cell == nil)
        {
            cell = [[MSEditUserCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.text = [item objectForKey:CELL_ITEM_KEY_TITLE];
        if (indexPath.section == 0)
        {
            cell.detailTextLabel.text = @"";
            if (selectImage) {
                [cell.imageView setImage:selectImage];
            }
            else
            {
                NSString *avatar = [[[MSSetting sharedSetting ]getAccountInfo] objectForKey:@"avatar"];
                if (avatar)
                {
                    [cell.imageView setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_img"]];
                }
            }
        }
        
    }
    else  if ([CellIdentifier intValue] == 1 || [CellIdentifier intValue] == 2 || [CellIdentifier integerValue] == 3)
    {
        if (cell == nil)
        {
            cell = [[MSEditUserCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
            
            if ([CellIdentifier intValue] == 2)
            {
                UIButton *sex_male = [self sexButton:CGRectMake(75, 7, 50, 30) title:HYLocalizedString(@"男")];
                sex_male.selected = (userSex==0)?YES:NO;
                sex_male.tag = 1;
                [cell.contentView addSubview:sex_male];
                
                UIButton *sex_female = [self sexButton:CGRectMake(130,7, 50, 30) title:HYLocalizedString(@"女")];
                sex_female.tag = 2;
                sex_female.selected = (userSex==1)?YES:NO;
                [cell.contentView addSubview:sex_female];
            }
            
            if ([CellIdentifier integerValue] == 3)
            {
                UITextField *textFiled=[[UITextField alloc]initWithFrame:CGRectZero];
                textFiled.delegate=self;
                textFiled.tag = 2;
                pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, 320, 216)];
                pickerView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
                pickerView.dataSource=self;
                pickerView.delegate=self;
                pickerView.showsSelectionIndicator=YES;
                textFiled.inputView = pickerView;
                [cell.contentView addSubview:textFiled];
            }
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.imageView.image = nil;
        cell.detailTextLabel.textColor = [UIColor blackColor];
        cell.textLabel.text = [item objectForKey:CELL_ITEM_KEY_TITLE];
        cell.detailTextLabel.text  = [item objectForKey:CELL_ITEM_KEY_VALUE];
        
        if ([cell.detailTextLabel.text length]<1)
        {
            cell.detailTextLabel.textColor = [UIColor grayColor];
            cell.detailTextLabel.text = HYLocalizedString(@"完善信息");
        }
        
        if ([CellIdentifier intValue] == 2||[CellIdentifier intValue] == 0)
        {
            if ([CellIdentifier intValue] == 2) {
                cell.detailTextLabel.text = @"";
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    
    if (indexPath.section == 1 || indexPath.row == 0)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

-(UIButton *)sexButton:(CGRect )rect title:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"search_price_normal"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"search_price_selected"] forState:UIControlStateSelected];
    [btn setImage:[UIImage imageNamed:@"search_price_selected"] forState:UIControlStateHighlighted];
    [btn.titleLabel setFont:FONT_NORMAL];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setFrame:rect];
    [btn addTarget:self action:@selector(selectSex:) forControlEvents:UIControlEventTouchDown];
    return btn;
}

-(void)selectSex:(UIButton *)btn
{
    for (UIView *v in btn.superview.subviews) {
        if ([v isKindOfClass:[UIButton class]]) {
            [(UIButton *)v setSelected:NO];
        }
    }
    userSex = btn.tag - 1;
    btn.selected = YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    selectItem = [[dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSString *content = [selectItem objectForKey:CELL_ITEM_KEY_VALUE];

    if (indexPath.section == 0)
    {
        [self selectImage];
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            return;
            [self enterInputPageTitle:HYLocalizedString(@"修改昵称") content:content];
        }
    }
    else if(indexPath.section == 2 )
    {
        [self enterInputPageTitle:HYLocalizedString(@"个人介绍") content:@""];
    }
    else if(indexPath.section == 3 )
    {
        if (indexPath.row == 0) {
            MSTagsVC *vc = [[MSTagsVC alloc]initWithNibName:@"MSTagsVC" tags:content];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if(indexPath.row == 1)
        {
            [self enterInputPageTitle:HYLocalizedString(@"编辑手机号码") content:content];
        }
        else if(indexPath.row == 2)
        {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            UITextField *txt = (UITextField *)[cell.contentView viewWithTag:2];
            [txt becomeFirstResponder];
            if ([proviceName length]<1 || [cityName length] < 1)
            {
                [self pickerView:self.pickerView didSelectRow:compoentOneSelectedIndex inComponent:0];
                [self pickerView:self.pickerView didSelectRow:compoentTwoSelectedIndex inComponent:1];
            }
            [self.pickerView selectRow:compoentOneSelectedIndex inComponent:0 animated:YES];
            [self.pickerView selectRow:compoentTwoSelectedIndex inComponent:1 animated:YES];
            [listTableView setContentOffset:CGPointMake(0, 160) animated:YES];
            maskView.hidden = NO;
        }
        else if(indexPath.row == 3)
        {
            [self enterInputPageTitle:HYLocalizedString(@"编辑沙龙") content:content];
        }
        else if(indexPath.row == 4)
        {
            [self enterInputPageTitle:HYLocalizedString(@"编辑电话") content:content];
        }
        else if(indexPath.row == 5)
        {
            [self enterInputPageTitle:HYLocalizedString(@"编辑地址") content:content];
        }
    }
}

-(void)enterInputPageTitle:(NSString * )title content:(NSString *)content
{
    MSEnterVC *vc = [[MSEnterVC alloc]initWithInitString:content title:title maxCount:MAX_INPUT_WORDS delegate:self];
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)didFinishAciton:(id)obj withInfo:(id)info
{
    HYLog(@"%@",info);
    [self updateData:info];
}


-(void)selectImage
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:HYLocalizedString(@"取消") destructiveButtonTitle:nil otherButtonTitles:HYLocalizedString(@"拍照"),HYLocalizedString(@"从相册选择"), nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [sheet showInView:self.navigationController.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    else if(buttonIndex == 0)
    {
        [self performSelector:@selector(takePhoto) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 1)
    {
        [self performSelector:@selector(openPhotoLibrary) withObject:nil afterDelay:0.0];
    }
}

-(void)openPhotoLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
}

//take a photo from camera
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		[self presentModalViewController:picker animated:YES];
	}
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"设备不支持拍照" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
    NSAssert(editImage != nil, @"Can't get the image!");
	if (editImage)
	{
        selectImage = editImage;
        [self.listTableView reloadData];
    }
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}


// Number of wheels
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}

// Number of rows per wheel
- (NSInteger)pickerView: (UIPickerView *)pView numberOfRowsInComponent: (NSInteger) component
{
	if (component == 0)
    {
		return [proviceArray count];
	}
	else if(component ==1)
    {
		return [areasArray count];
	}
	else
    {
		return 0;
	}
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	if (component == 0)
    {
		return [[proviceArray objectAtIndex:row] objectForKey:@"name"];
	}
	else if (component == 1)
    {
		return [[areasArray objectAtIndex:row] objectForKey:@"name"];
	}
	
	return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	NSLog(@"row %d component %d", row, component);
	
    if (component == 0)
    {
        compoentOneSelectedIndex = row;
        
        compoentTwoSelectedIndex = 0;
        
		[areasArray removeAllObjects];
        NSString *pid = [[proviceArray objectAtIndex:row] objectForKey:@"id"];
        
        [userInfo setObject:pid forKey:@"province_id"];
        
		[areasArray addObjectsFromArray:[provices objectForKey:pid]];
		[self.pickerView selectRow:0 inComponent:1 animated:NO];
		[self.pickerView reloadComponent:1];
        proviceName = [[proviceArray objectAtIndex:row] objectForKey:@"name"];
        
        if ([areasArray count]>0)
            cityName = [[areasArray objectAtIndex:0] objectForKey:@"name"];
        
        NSString *cid = [[areasArray objectAtIndex:0] objectForKey:@"id"];
        
        if (cid && [cid length]>0)[userInfo setObject:cid forKey:@"city_id"];
	}
	else if (component == 1)
    {
        compoentTwoSelectedIndex = row;
        
        cityName = [[areasArray objectAtIndex:row] objectForKey:@"name"];
        
        NSString *cid = [[areasArray objectAtIndex:row] objectForKey:@"id"];
        
        if (cid && [cid length]>0)[userInfo setObject:cid forKey:@"city_id"];
	}
    HYLog(@"userInfo-->%@",userInfo);
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:3];
    UITableViewCell *cell = [listTableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",proviceName,cityName];
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	if (component == 0)
    {
		return 80; // province
	}
	else {
		return 240; // crses
	}
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
